package com.bbg.amyam.web.flow.service.schoolPublicView.requestPasswordReset;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;

import com.bbg.amyam.domain.model.PasswordRetrieveKey;
import com.bbg.amyam.domain.model.Profile;
import com.bbg.amyam.domain.model.School;
import com.bbg.amyam.process.jms.queue.PasswordResetMessage;
import com.bbg.amyam.process.jms.queue.QueueEventAgent;
import com.bbg.amyam.web.flow.service.WebFlowService;
import com.bbg.amyam.web.flow.service.schoolPublicView.retrievePassword.RetrievePasswordForm;
import com.bbg.amyam.web.mvc.exception.NoSchoolFoundException;
import com.bbg.amyam.web.util.RequestPathParameter;
import com.bbg.amyam.web.util.RequestPathPaser;

@Service("requestPasswordResetService")
public class RequestPasswordResetServiceImpl extends WebFlowService implements
		RequestPasswordResetService {

	@Autowired
	private QueueEventAgent queueEventAgent;

	private RequestPasswordResetForm getForm(RequestContext context) {
		return (RequestPasswordResetForm) context.getFlowScope().get(
				"requestPasswordResetForm");
	}

	public Event sendPasswordRetrieveKeyAction(RequestContext context) {
		RequestPasswordResetForm form = getForm(context);
		String email = form.getEmail();
		List<Profile> profiles = Profile.findProfilesByEmailEquals(email)
				.getResultList();
		try {
			if (profiles.size() > 0) {
				Profile profile = profiles.get(0);
				School school = loadCurrentSchool();
				RequestPathParameter param;

				param = RequestPathPaser.parse((HttpServletRequest) context
						.getExternalContext().getNativeRequest());

				PasswordResetMessage queueMessage = new PasswordResetMessage();
				queueMessage.setProfileId(profile.getId());
				queueMessage.setSchoolShortName(school.getShortName());
				queueMessage.setRequestURL(param.getRequestURL());
				queueEventAgent.sendMessage(queueMessage);
				return success();
			} else {
				form.setMessage("The email address could not be found in our system. Please try again.");
			}
		} catch (NoSchoolFoundException e) {
			e.printStackTrace();
			form.setMessage(e.getMessage());
		}
		return error();

	}
}
